<template>
  <div class="resource-tools">
    <div class="tool-recommendation" v-if="categories.length > 1">
      <div class="categories">
        <span
            :class="{ active: selectedCategory === category.id }"
            :key="category.id"
            @click="selectCategory(category.id)"
            class="category-button"
            v-for="category in categories"
        >
          {{ category.name }}
        </span>
      </div>
      <div class="tools-grid">
        <div
            :key="tool.id"
            class="tool-card"
            v-for="tool in filteredTools"
        >
          <div class="tool-header">
            <h3>{{ tool.name }}</h3>
            <span class="tool-category">[{{ tool.category.name }}]</span>
          </div>
          <img :src="tool?.image || 'https://picsum.photos/200/150'" alt="{{ tool.name }}" class="tool-logo"/>
          <p class="tool-description">{{ tool.desc }}</p>
          <div class="tool-actions">
            <a :href="tool.route" class="entry-button" rel="noopener noreferrer" target="_blank"
               v-if="tool.is_official">进入</a>
            <a :href="tool.link" class="entry-button" rel="noopener noreferrer" target="_blank" v-else>进入</a>
          </div>
        </div>
      </div>
      <ArticlePagination
          :currentPage="currentPage"
          :page_size="pageSize"
          :totalItems="totalItems"
          :totalPages="totalPages"
          @page-change="handlePageChange"
      />
    </div>
    <div v-else class="no-recommendation">
      <p>暂无推荐工具</p>
    </div>
  </div>
</template>

<script setup>
import ArticlePagination from "@/components/articles/ArticlePagination.vue";

const selectedCategory = ref('')
const categories = ref([])
const tools = ref([])
const underlinePosition = ref(0)
// 页码相关
const currentPage = ref(1)
const pageSize = ref(1) // 每页条数
const totalPages = ref(0) // 总页数
const totalItems = ref(0) // 总条数

const handlePageChange = (page) => {
  currentPage.value = page
  fetchTools()
}

const filteredTools = computed(() => {
  if (!selectedCategory.value || selectedCategory.value === '全部') {
    return tools.value
  }
  return tools.value.filter(tool => tool.category.id === selectedCategory.value)
})

const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  currentPage.value = 1 // 切换分类时重置为第一页
  fetchTools() // 重新获取工具数据
  nextTick(() => {
    const categoryIndex = categories.value.findIndex(cat => cat.id === categoryId)
    const categoryButton = document.querySelector(`.category-button:nth-child(${categoryIndex + 1})`)

    if (categoryButton) {
      underlinePosition.value = categoryButton.offsetLeft + (categoryButton.offsetWidth / 2) - 30
    }
  })
}

const fetchTools = async () => {
  try {
    const response = await axios.get('/api/resources/tools/', {params: {page: currentPage.value, category: selectedCategory.value}})
    tools.value = response.data.results
    pageSize.value = response.data.page_size
    currentPage.value = response.data.page
    totalPages.value = response.data.total_pages
    totalItems.value = response.data.count
  } catch (error) {
    console.error('获取工具数据失败:', error)
  }
}

const fetchCategories = async () => {
  try {
    const response = await axios.get('/api/resources/tools/categories/')
    categories.value = [...response.data]
    categories.value.unshift({id: '', name: '全部'})
  } catch (error) {
    console.error('获取分类数据失败:', error)
  }
}

onMounted(async () => {
  await fetchCategories()
  await fetchTools()
  selectCategory(categories.value[0].id)
})

</script>

<style scoped>
/* 页面整体布局 */
.resource-tools {
  margin: 10px auto;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  min-height: 100vh;
  width: auto;
}

/* 分类导航部分 */
.tool-recommendation {
  width: 100%;
  padding: 20px 0;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.categories {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: flex-start; /* 调整分类按钮的对齐方式 */
}

.category-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border-radius: 15px; /* 圆角设计 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 增加阴影效果 */
  cursor: pointer;
  color: var(--resources-shadow-text-color, #333);
  background-color: var(--resources-shadow-color, #fff); /* 背景颜色 */
  transition: background-color 0.3s, box-shadow 0.3s;
}

.category-button.active {
  background-color: var(--resources-active-color, #96b7e8);
  color: var(--resources-active-text-color, #fff);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.category-button:hover {
  background-color: #e0e0e0;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

/* 工具卡片部分 */
.tools-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(232px, 1fr)); /* 自适应网格布局 */
  gap: 20px; /* 卡片间距 */
  margin-top: 15px; /* 顶部间距 */
}

.tool-card {
  background-color: var(--resources-bg-color, #fff);
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  display: flex;
  flex-direction: column;
}

.tool-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.tool-header {
  display: flex;
  justify-content: space-between; /* 调整标题和分类的对齐方式 */
  align-items: center;
  margin-bottom: 10px;
}

.tool-header h3 {
  font-size: 14px;
  font-weight: bold;
  margin: 0;
  color: var(--resources-title-color, #333);
}

.tool-category {
  font-size: 12px;
  color: var(--resources-text-color, #999);
}

.tool-logo {
  width: 100%;
  height: 100px;
  object-fit: cover;
  margin-bottom: 10px;
  border-radius: 5px;
}

.tool-description {
  font-size: 12px;
  color: var(--resources-desc-color, #999);
  margin: 10px 0;
}

.tool-actions {
  display: flex;
  justify-content: flex-end; /* 将按钮右对齐 */
  margin-top: auto; /* 将按钮移到底部 */
}

.entry-button {
  background-color: var(--resources-button-bg-color, #00c6ff);
  color: var(--resources-button-text-color, #fff);
  padding: 4px 8px;
  border-radius: 5px;
  text-decoration: none;
  transition: background-color 0.3s;
}

.entry-button:hover {
  background-color: var(--resources-button-hover-bg-color, #0099cc);
}

.no-recommendation {
  text-align: center;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 1em;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 678px) {
  .categories {
    justify-content: center; /* 小屏幕设备上居中对齐 */
  }

  .category-button {
    padding: 10px 15px;
    margin-bottom: 10px;
  }

  .tools-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); /* 小屏幕网格布局 */
  }
}
@media (max-width: 480px) {
  .categories {
    justify-content: flex-start; /* 移动设备上左对齐 */
  }
  .category-button {
    padding: 6px 10px;
    font-size: 12px;
  }
}
</style>
